package com.weiqiao.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.Gson;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CarouseEntity;
import com.weiqiao.mall.domain.LabelShelfEntity;
import com.weiqiao.mall.repository.ILabelShelfRepository;
import com.weiqiao.mall.repository.ISlideshowRepository;
import com.weiqiao.mall.service.ILabelShelfService;
import com.weiqiao.mall.service.vo.CascadeVO;
import com.weiqiao.utils.MallUtil;
import com.weiqiao.utils.StringUtils;
import com.weiqiao.utils.WeiXinUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 宝贝标签service实现类
 * @author: xujun
 * @Date: 2019/10/31  10:42
 */
@Log4j
@Service("labelShelfService")
public class LabelShelfServiceImpl implements ILabelShelfService {

    @Autowired
    private ILabelShelfRepository labelShelfRepository;

    @Autowired
    private ISlideshowRepository slideshowRepository;

    /**
     * 查询宝贝标签列表数据
     *
     * @param request
     * @return
     */
    @Override
    public Map getLabelShelfData(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        Bson filter = Filters.eq("delete_flag", 0);
        List<String> list = labelShelfRepository.getLabelShelfList(companyId, filter);
        List<Map> resultList = new ArrayList<>();
        Document slide_doc = new Document("company_id", companyId);
        slide_doc.append("delete_flag", 0);
        List<String> carouseStrList = slideshowRepository.getCarouseList(slide_doc);
        Map<String, String> carouseUrlMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(carouseStrList)) {
            for (String str : carouseStrList) {
                CarouseEntity carouseEntity = new Gson().fromJson(str, CarouseEntity.class);
                carouseUrlMap.put(carouseEntity.getCarouse_id(), (CollectionUtils.isNotEmpty(carouseEntity.getCarouseList()) ?
                    carouseEntity.getCarouseList().get(0).getUrl() : ""));
            }
        }
        if (CollectionUtils.isNotEmpty(list)) {
            for (String entity : list) {
                LabelShelfEntity labelShelfEntity = new Gson().fromJson(entity, LabelShelfEntity.class);
                Map map = new HashMap(7);
                map.put("id", labelShelfEntity.getLabel_shelf_id());
                map.put("name", labelShelfEntity.getLabel_shelf_name());
                map.put("parent_id", "0");
                map.put("url", labelShelfEntity.getLabel_shelf_src());
                map.put("rotation_url", (carouseUrlMap.get(labelShelfEntity.getCarouse_id()) == null ? ""
                        : carouseUrlMap.get(labelShelfEntity.getCarouse_id())));
                map.put("remark", labelShelfEntity.getLabel_shelf_describe());
                map.put("carouse_id", labelShelfEntity.getCarouse_id());
                List<LabelShelfEntity.LabelBrand> label_brand_list = labelShelfEntity.getLabel_brand_list();
                List<Map> childrenList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(label_brand_list)) {
                    for (LabelShelfEntity.LabelBrand labelBrand : label_brand_list) {
                        Map childrenMap = new HashMap(6);
                        childrenMap.put("id", labelBrand.getLabel_brand_id());
                        childrenMap.put("name", labelBrand.getLabel_brand_name());
                        childrenMap.put("parent_id", labelShelfEntity.getLabel_shelf_id());
                        childrenMap.put("url", labelBrand.getLabel_brand_src());
                        childrenMap.put("carouse_id", labelBrand.getCarouse_id());
                        childrenMap.put("rotation_url", (carouseUrlMap.get(labelBrand.getCarouse_id()) == null ? ""
                                : carouseUrlMap.get(labelBrand.getCarouse_id())));
                        childrenMap.put("remark", labelBrand.getLabel_brand_introduce());
                        childrenList.add(childrenMap);
                    }
                }
                // 二维数据最后一条需要加一条空值
                childrenList.add(this.getChildrenMap(WeiXinUtils.getUUID(), labelShelfEntity.getLabel_shelf_id()));
                map.put("children", childrenList);
                resultList.add(map);
            }
        } else {
            // 当没有数据时造一条空数据
            Map parentMap = new HashMap(7);
            String currentTime = String.valueOf(System.currentTimeMillis());
            parentMap.put("id", currentTime);
            parentMap.put("name", "");
            parentMap.put("parent_id", "0");
            parentMap.put("url", "");
            parentMap.put("rotation_url", "");
            parentMap.put("remark", "");
            parentMap.put("carouse_id", "");
            List<Map> childrenList = new ArrayList<>();
            // 二维数据最后一条需要加一条空值
            childrenList.add(this.getChildrenMap(WeiXinUtils.getUUID(),currentTime));
            parentMap.put("children", childrenList);
            resultList.add(parentMap);
        }
        Map resultMap = new HashMap(1);
        resultMap.put("content", resultList);
        return resultMap;
    }

    /**
     * 宝贝标签，二维数据添加一条空值
     * @param id
     * @param pid
     * @return
     */
    private Map getChildrenMap(String id, String pid) {
        Map childrenMap = new HashMap(6);
        childrenMap.put("id", id);
        childrenMap.put("name", "");
        childrenMap.put("parent_id", pid);
        childrenMap.put("url", "");
        childrenMap.put("rotation_url", "");
        childrenMap.put("remark", "");
        return childrenMap;
    }

    /**
     * 保存宝贝标签
     *
     * @param request
     * @return
     */
    @Override
    public ResponseEntity saveLabel(HttpServletRequest request) {
        int companyId = MallUtil.getCompanyId(request);
        // 先获取删除的id，保存之前先删除数据
        String delLabelIdStr = MallUtil.getString(request, "del_label_id", "");
        String[] split = delLabelIdStr.split(",");
        if (split != null && split.length > 0) {
            for (String labelId : split) {
                // 执行删除，首先判断当前的id是 一级标签还是二级标签
                Bson query = Filters.and(Filters.eq("delete_flag", 0), Filters.eq("label_shelf_id", labelId));
                String labelShelfByFilter = labelShelfRepository.getLabelShelfByFilter(companyId, query);
                // 如果是一级标签只修改状态为逻辑删除, 二级标签不用管，二级标签在保存的时候是直接覆盖原来的数据
                if (StringUtils.isNotBlank(labelShelfByFilter)) {
                    Document document = Document.parse(labelShelfByFilter);
                    document.append("delete_flag", 1);
                    labelShelfRepository.findAndUpdate(companyId, query, document, false);
                }
            }
        }
        //获取json数据
        String labelJsonStr = request.getParameter("label_data");
        Map resultMap = new HashMap(2);
        if (StringUtils.isBlank(labelJsonStr)) {
            resultMap.put("result", false);
            resultMap.put("msg", "没有数据需要保存");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        //转成list集合
        List<Map<String, Object>> parseObject = JSONArray.parseObject(labelJsonStr, List.class);
        if (CollectionUtils.isEmpty(parseObject)) {
            resultMap.put("result", false);
            resultMap.put("msg", "没有数据需要保存");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        // 执行保存
        try {
            for (Map map : parseObject) {
                String label_shelf_id = MapUtils.getString(map, "id", "");
                if (StringUtils.isBlank(label_shelf_id)) {
                    label_shelf_id = WeiXinUtils.getUUID();
                }
                String label_shelf_name = MapUtils.getString(map, "name", "");
                String label_shelf_src = MapUtils.getString(map, "url", "");
                String label_shelf_describe = MapUtils.getString(map, "remark", "");
                String carouse_id = MapUtils.getString(map, "carouse_id", "");
                if (StringUtils.isBlank(label_shelf_name) && StringUtils.isBlank(label_shelf_src) && StringUtils.isBlank(label_shelf_describe)) {
                    continue;
                }
                List<Map<String, String>> childrenListMap = new ArrayList<>();
                Object children = map.get("children");
                if (children != null && children instanceof List) {
                    List<Map<String, String>> childrenList = (List<Map<String, String>>) children;
                    if (CollectionUtils.isNotEmpty(childrenList)) {
                        for (Map<String, String> stringMap : childrenList) {
                            String label_brand_id = MapUtils.getString(stringMap, "id", "");
                            if (StringUtils.isBlank(label_brand_id)) {
                                label_brand_id = WeiXinUtils.getUUID();
                            }
                            String label_brand_name = MapUtils.getString(stringMap, "name", "");
                            String label_brand_src = MapUtils.getString(stringMap, "url", "");
                            String label_rotation_chart_src = MapUtils.getString(stringMap, "rotation_url", "");
                            String label_brand_introduce = MapUtils.getString(stringMap, "remark", "");
                            String brand_carouse_id = MapUtils.getString(stringMap, "carouse_id", "");
                            if (StringUtils.isBlank(label_brand_name) && StringUtils.isBlank(label_brand_src) && StringUtils.isBlank(label_rotation_chart_src) && StringUtils.isBlank(label_brand_introduce)) {
                                continue;
                            }
                            Map<String, String> m = new HashMap<>(5);
                            m.put("label_brand_id", label_brand_id);
                            m.put("label_brand_name", label_brand_name);
                            m.put("label_brand_src", label_brand_src);
                            m.put("carouse_id", brand_carouse_id);
                            m.put("label_brand_introduce", label_brand_introduce);
                            childrenListMap.add(m);
                        }
                    }
                }
                Document document = new Document();
                document.append("label_shelf_name", label_shelf_name);
                document.append("label_shelf_src", label_shelf_src);
//                document.append("rotation_chart_src", rotation_chart_src);
                document.append("label_shelf_describe", label_shelf_describe);
                document.append("label_brand_list", childrenListMap);
                document.append("carouse_id", carouse_id);
                //编辑false  新增true
                Bson filter = Filters.and(Filters.eq("label_shelf_id", label_shelf_id), Filters.eq("delete_flag", 0));
                String jsonStr = labelShelfRepository.getLabelShelfByFilter(companyId, filter);
                boolean bool = StringUtils.isBlank(jsonStr);
                if (bool) {
                    document.append("type", 1);
                    document.append("label_shelf_id", label_shelf_id);
                }
                labelShelfRepository.findAndUpdate(companyId, filter, document, bool);
            }
        } catch (Exception e) {
            log.error("保存宝贝标签失败", e);
            resultMap.put("result", false);
            resultMap.put("msg", "保存失败");
            return new ResponseEntity(resultMap, HttpStatus.OK);
        }
        resultMap.put("result", true);
        resultMap.put("msg", "保存成功");
        return new ResponseEntity(resultMap, HttpStatus.OK);
    }

    /**
     * 标签list转换为实体类
     * @param companyId 公司id
     * @param filter 查询条件
     * @return
     */
    private List<LabelShelfEntity> getLabelList(int companyId, Document filter) {
        List<LabelShelfEntity> list = new ArrayList<>();
        List<String> stringsList = labelShelfRepository.getLabelShelfList(companyId, filter);
        if (CollectionUtils.isEmpty(stringsList)) return list;
        Gson gson = new Gson();
        for (String info: stringsList) {
            LabelShelfEntity entity = gson.fromJson(info, LabelShelfEntity.class);
            list.add(entity);
        }
        return list;
    }

    @Override
    public List<CascadeVO> getLabelCascadeList(int companyId) {
        // 获取已经转换好的标签实体集合，查询条件为，未删除的标签
        List<LabelShelfEntity> labelList = this.getLabelList(companyId, new Document("delete_flag", 0));
        // 把标签实体转换为级联选择器实体类
        List<CascadeVO> list = new ArrayList<>();
        for (LabelShelfEntity entity : labelList) {
            CascadeVO info = new CascadeVO();
            info.setValue(entity.getLabel_shelf_id());
            info.setLabel(entity.getLabel_shelf_name());
            // 二级标签不为空
            if (CollectionUtils.isNotEmpty(entity.getLabel_brand_list())) {
                List<CascadeVO.CascadeChildrenVo> childrenVoList = new ArrayList<>();
                for (LabelShelfEntity.LabelBrand pojo : entity.getLabel_brand_list()) {
                    CascadeVO.CascadeChildrenVo children = new CascadeVO.CascadeChildrenVo();
                    children.setValue(pojo.getLabel_brand_id());
                    children.setLabel(pojo.getLabel_brand_name());
                    childrenVoList.add(children);
                }
                info.setChildren(childrenVoList);
            }
            list.add(info);
        }
        return list;
    }
}
